package com.youngthing.webstorm.plugin.vue.action;

import com.intellij.icons.AllIcons;
import com.intellij.lang.javascript.psi.JSEmbeddedContent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.impl.source.html.HtmlDocumentImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.io.IOUtil;
import com.twelvemonkeys.io.FileUtil;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

/**
 * vue文件与js文件的分离
 *
 * @author Ryan
 * @since 0.0.1
 */
public class VueJsAction extends AnAction {
    private static final Logger logger = LoggerFactory.getLogger(VueJsAction.class);

    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        PsiElement data = anActionEvent.getData(PlatformDataKeys.PSI_ELEMENT);
        logger.info("{}", data);
        final PsiElement child = data.getChildren()[0];
        logger.info("{}", child.getClass());
        if (child instanceof HtmlDocumentImpl) {
            final HtmlDocumentImpl htmlDocument = (HtmlDocumentImpl) child;
            // PsiTreeUtil.findChildOfType();
            final Collection<HtmlTag> tags = PsiTreeUtil.findChildrenOfType(child, HtmlTag.class);
            for (HtmlTag tag : tags) {
                final boolean javascript = tag.getName().endsWith("script");
                if (javascript) {
                    final JSEmbeddedContent jsembeddedContent = PsiTreeUtil.getChildOfType(tag, JSEmbeddedContent.class);
                    if (jsembeddedContent != null) {
                        moveJavascript(anActionEvent, data, tag, jsembeddedContent);
                    }
                }
            }
        }
    }

    private void moveJavascript(@NotNull AnActionEvent anActionEvent, PsiElement data, HtmlTag tag, JSEmbeddedContent jsembeddedContent) {
        final String text = jsembeddedContent.getText();

        final PsiFile containingFile = data.getContainingFile();
        final VirtualFile virtualFile = containingFile.getVirtualFile();
        final VirtualFile dir = virtualFile.getParent();
        // 新建一个文件，然后把js内容写进去
        final Project project = anActionEvent.getProject();
        final Messages.InputDialog inputDialog = new Messages.InputDialog(project,
                "请输入文件名", "提示",
                AllIcons.FileTypes.Java,
                "main.js",
                new InputValidator() {
                    @Override
                    public boolean checkInput(String inputString) {
                        final VirtualFile dirChild = dir.findChild(inputString);
                        return dirChild == null;
                    }

                    @Override
                    public boolean canClose(String inputString) {
                        return true;
                    }
                });

        if (inputDialog.showAndGet()) {
            final String inputString = inputDialog.getInputString();
            write(text.trim(), dir, project, inputString, jsembeddedContent, tag);

        }
    }

    private void write(String text, VirtualFile dir, Project project, String fileName, JSEmbeddedContent jsembeddedContent, HtmlTag tag) {
        WriteCommandAction.runWriteCommandAction(project,
                () -> {
                    try {
                        final VirtualFile childData = dir.createChildData(this, fileName);
                        try (OutputStream outputStream = childData.getOutputStream(this);
                             PrintStream printWriter = new PrintStream(outputStream, true, StandardCharsets.UTF_8.name())) {
                            printWriter.println(text);
                        }
                    } catch (IOException e) {
                        logger.error("actionPerformed", e);
                    }
                    // 原先的元素内容要去掉。
                    jsembeddedContent.delete();
                    // 加上src属性
                    tag.setAttribute("src","./" +  fileName);

                });
    }
}
